<?php
App::import ( 'Model', 'JobType' );
class JobsController extends AppController {
	
	public function beforeFilter() {
		parent::beforeFilter ();
	}
	
	public function index() {
		$this->Job->recursive = 0;
		$this->set ( 'jobs', $this->paginate () );
	}
	
	public function view($id = null) {
		$this->Job->recursive = 2;
		$this->Job->id = $id;
		if (! $this->Job->exists ()) {
			throw new NotFoundException ( __ ( 'Invalid job id' ) );
		}
		
		$this->set ( 'job', $this->Job->read ( null, $id ) );
	}
	
	public function add() {
		if ($this->request->is ( 'post' )) {
			$this->Job->create ();
			$JobType = new JobType ();
			if ($this->Job->save ( $this->request->data )) {
				$types = $this->request->data ['JobType'];
				$types_size = count ( $JobType->find ( 'all' ) );
				for($i = 1; $i <= $types_size; $i ++) {
					if (isset ( $types [$i] )) {
						$jobType = new JobType ();
						$jobType->set ( 'job_id', $this->Job->id );
						$jobType->set ( 'type_id', $i );
						$jobType->save ();
					}
				}
				$this->Session->setFlash ( __ ( 'The new job has been created' ) );
				$this->redirect ( array ('action' => 'index' ) );
			} else {
				$this->Session->setFlash ( __ ( 'The job could not be saved. Please check your data and try again.' ) );
			}
		}
	}
	
	public function edit($id = null) {
		$this->Job->id = $id;
		if (! $this->Job->exists ()) {
			throw new NotFoundException ( __ ( 'Invalid job' ) );
		}
		if ($this->request->is ( 'post' ) || $this->request->is ( 'put' )) {
			if ($this->Job->save ( $this->request->data )) {
				$this->Session->setFlash ( __ ( 'The job has been saved' ) );
				$this->redirect ( array ('action' => 'index' ) );
			} else {
				$this->Session->setFlash ( __ ( 'The job could not be saved. Please, try again.' ) );
			}
		} else {
			$this->request->data = $this->Job->read ( null, $id );
		}
	}
	
	public function delete($id = null) {
		if (! $this->request->is ( 'post' )) {
			throw new MethodNotAllowedException ();
		}
		$this->Job->id = $id;
		if (! $this->Job->exists ()) {
			throw new NotFoundException ( __ ( 'Invalid job' ) );
		}
		if ($this->Job->delete ()) {
			$this->Session->setFlash ( __ ( 'Job deleted' ) );
			$this->redirect ( array ('action' => 'index' ) );
		}
		$this->Session->setFlash ( __ ( 'Job was not deleted' ) );
		$this->redirect ( array ('action' => 'index' ) );
	}
}